package com.flyox.game.militarychess.client.view;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Hashtable;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.Timer;
import javax.swing.WindowConstants;
import javax.swing.border.LineBorder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

import com.flyox.game.militarychess.CONSTS;
import com.flyox.game.militarychess.bean.ChessDesk;
import com.flyox.game.militarychess.bean.ChessMan;
import com.flyox.game.militarychess.bean.ChessDesk.DESK_STATE;
import com.flyox.game.militarychess.bean.ChessSeat.SEAT_NAME;
import com.flyox.game.militarychess.client.control.MainControl;
import com.flyox.game.militarychess.client.services.DataService;
import com.flyox.game.militarychess.message.BoardBean;
import com.flyox.game.militarychess.message.ChessPackage;
import com.flyox.game.militarychess.message.Request;
import com.flyox.game.militarychess.message.Response;
import com.flyox.game.militarychess.service.CommonLayoutService;
import com.flyox.game.militarychess.util.Secret;
import com.flyox.game.militarychess.util.SerialUtil;

public class ChessFrame extends javax.swing.JFrame /* implements WindowListener */{
	{
		// Set Look & Feel
		try {
			javax.swing.UIManager.setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private static final long serialVersionUID = -6790002063541720157L;
	private final Logger logger = LoggerFactory.getLogger(getClass());
	DataService dataService = new DataService();
	CommonLayoutService commonLayoutService = new CommonLayoutService();

	private JPanel ControlPanel;
	private JPanel MessagePanel;
	private JPanel statePanel;
	private JScrollPane jScrollPane1;
	private JLabel jLabelPosMessage;
	private JButton jButtonExit;
	private JButton jButtonReady;
	private JPanel otherPanel;
	private JPanel mainPanel;

	private DeskLayoutJPanel deskLayoutJPanel;
	private Image iconImage;
	private HallDeskPanel dp[];
	private JButton jButton2;
	private JButton jButtonHelp;
	private JProgressBar jProgressBarTimer;
	private JLabel jLabelCurrentPlayer;
	private JLabel jLabelSysMsg;
	private JButton jButtonSurrender;
	private JPanel hallPanel;
	private JButton jButton1;

	private MediaTracker tracker;
	public Image emptyImage;
	public Image busyImage;
	public BufferedImage s1_allChessImage;
	public BufferedImage s2_allChessImage;
	public BufferedImage s3_allChessImage;
	public BufferedImage s4_allChessImage;
	public BufferedImage s5_allChessImage;
	public BufferedImage s6_allChessImage;
	public BufferedImage s7_allChessImage;
	public BufferedImage s8_allChessImage;

	public MainControl control;
	CardLayout mainPanelCardLayout = new CardLayout();
	AudioStream ringwav;
	AudioStream beginwav;
	AudioStream startwav;
	AudioStream bombwav;
	AudioStream deadwav;
	AudioStream eatwav;
	AudioStream killedwav;
	AudioStream movewav;
	AudioStream selectwav;
	AudioStream showflagwav;
	AudioStream timerwav;

	Timer countTimer;
	public static int defaultTimeCount = 10;
	public static int currentTimeCount = 10;

	public ChessFrame(MainControl control) {
		super();
		this.control = control;
		initGUI();
		initHallPanel();
	}

	public BufferedImage getQiZiImage(SEAT_NAME team) {
		switch (team) {
		case S1:
			return s1_allChessImage;
		case S2:
			return s2_allChessImage;
		case S3:
			return s3_allChessImage;
		case S4:
			return s4_allChessImage;
		case S5:
			return s5_allChessImage;
		case S6:
			return s6_allChessImage;
		case S7:
			return s7_allChessImage;
		case S8:
			return s8_allChessImage;
		default:
			break;
		}
		return null;
	}

	private void initGUI() {
		try {
			// this.setUndecorated(true);//不显示标题栏
			// getGraphicsConfiguration().getDevice().setFullScreenWindow(this);//全屏显示

			// load media
			tracker = new MediaTracker(this);
			Toolkit toolkit = Toolkit.getDefaultToolkit();
			emptyImage = toolkit.getImage(this.getClass().getResource("/com/flyox/game/militarychess/client/res/img/empty_desk.png"));
			busyImage = toolkit.getImage(this.getClass().getResource("/com/flyox/game/militarychess/client/res/img/empty_desk.png"));
			iconImage = toolkit.getImage(this.getClass().getResource("/com/flyox/game/militarychess/client/res/img/icon.gif"));
			tracker.addImage(emptyImage, 1);
			tracker.addImage(busyImage, 1);
			tracker.addImage(iconImage, 1);
			try {
				tracker.waitForID(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			// getInsets();
			//
			try {
				s1_allChessImage = ImageIO.read(this.getClass().getResource("/com/flyox/game/militarychess/client/res/img/s1.bmp"));
				s2_allChessImage = ImageIO.read(this.getClass().getResource("/com/flyox/game/militarychess/client/res/img/s2.bmp"));
				s3_allChessImage = ImageIO.read(this.getClass().getResource("/com/flyox/game/militarychess/client/res/img/s3.bmp"));
				s4_allChessImage = ImageIO.read(this.getClass().getResource("/com/flyox/game/militarychess/client/res/img/s4.bmp"));
				s5_allChessImage = ImageIO.read(this.getClass().getResource("/com/flyox/game/militarychess/client/res/img/s5.bmp"));
				s6_allChessImage = ImageIO.read(this.getClass().getResource("/com/flyox/game/militarychess/client/res/img/s6.bmp"));
				s7_allChessImage = ImageIO.read(this.getClass().getResource("/com/flyox/game/militarychess/client/res/img/s7.bmp"));
				s8_allChessImage = ImageIO.read(this.getClass().getResource("/com/flyox/game/militarychess/client/res/img/s8.bmp"));

				ringwav = new AudioStream(getClass().getResourceAsStream("/com/flyox/game/militarychess/client/res/wav/ring.wav"));
				beginwav = new AudioStream(getClass().getResourceAsStream("/com/flyox/game/militarychess/client/res/wav/begin.wav"));
				startwav = new AudioStream(getClass().getResourceAsStream("/com/flyox/game/militarychess/client/res/wav/start.wav"));
				bombwav = new AudioStream(getClass().getResourceAsStream("/com/flyox/game/militarychess/client/res/wav/bomb.wav"));
				deadwav = new AudioStream(getClass().getResourceAsStream("/com/flyox/game/militarychess/client/res/wav/dead.wav"));
				eatwav = new AudioStream(getClass().getResourceAsStream("/com/flyox/game/militarychess/client/res/wav/eat.wav"));
				killedwav = new AudioStream(getClass().getResourceAsStream("/com/flyox/game/militarychess/client/res/wav/killed.wav"));
				movewav = new AudioStream(getClass().getResourceAsStream("/com/flyox/game/militarychess/client/res/wav/move.wav"));
				selectwav = new AudioStream(getClass().getResourceAsStream("/com/flyox/game/militarychess/client/res/wav/select.wav"));
				showflagwav = new AudioStream(getClass().getResourceAsStream("/com/flyox/game/militarychess/client/res/wav/showflag.wav"));
				timerwav = new AudioStream(getClass().getResourceAsStream("/com/flyox/game/militarychess/client/res/wav/timer.wav"));
			} catch (IOException e) {
				e.printStackTrace();
			}
			// setExtendedState(MAXIMIZED_BOTH);
			this.setLocation(0, 0);
			this.setTitle("八国军旗--》" + dataService.getPlayer().getName());
			this.setIconImage(iconImage);
			addWindowListener(new WindowAdapter() {
				public void windowClosing(WindowEvent e) {
					System.out.println("onclosed");
					// control.getMinaClient().close();
					dispose();
					System.exit(0);
				}
			});
			setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
			{
				ControlPanel = new JPanel();
				FlowLayout ControlPanelLayout = new FlowLayout();
				ControlPanelLayout.setAlignment(FlowLayout.LEFT);
				ControlPanel.setLayout(ControlPanelLayout);
				getContentPane().add(ControlPanel, BorderLayout.NORTH);
				ControlPanel.setPreferredSize(new java.awt.Dimension(1016, 0));
			}
			{
				MessagePanel = new JPanel();
				MessagePanel.setLayout(null);
				getContentPane().add(MessagePanel, BorderLayout.EAST);
				MessagePanel.setPreferredSize(new java.awt.Dimension(98, 675));
				MessagePanel.setSize(98, 678);
				{
					jButtonSurrender = new JButton();
					MessagePanel.add(jButtonSurrender);
					jButtonSurrender.setText("\u6295\u964d");
					jButtonSurrender.setBounds(7, 98, 86, 22);
					jButtonSurrender.setEnabled(false);
					jButtonSurrender.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							jButtonSurrenderActionPerformed(evt);
						}
					});
				}
				{
					jButtonReady = new JButton();
					MessagePanel.add(jButtonReady);
					jButtonReady.setText("完成调度");
					jButtonReady.setBounds(7, 55, 86, 22);
					jButtonReady.setEnabled(false);
					jButtonReady.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							jButtonReadyActionPerformed(evt);
						}
					});
				}
				{
					jButtonExit = new JButton();
					MessagePanel.add(jButtonExit);
					jButtonExit.setText("退出");
					jButtonExit.setBounds(7, 185, 86, 22);
					jButtonExit.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							jButtonExitActionPerformed(evt);
						}
					});
				}
				{
					jButton1 = new JButton();
					jButton1.setToolTipText("hello");
					MessagePanel.add(jButton1);
					jButton1.setText("test");
					jButton1.setBounds(7, 455, 86, 22);
					jButton1.setBorder(BorderFactory.createCompoundBorder(new LineBorder(new java.awt.Color(0, 255, 64), 2, true), new LineBorder(new java.awt.Color(255, 0, 0), 2, true)));
					jButton1.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							jButton1ActionPerformed(evt);
						}
					});
				}
				{
					jProgressBarTimer = new JProgressBar(0, defaultTimeCount);
					MessagePanel.add(jProgressBarTimer);
					jProgressBarTimer.setBounds(7, 141, 86, 22);
					jProgressBarTimer.setStringPainted(true);
					jProgressBarTimer.setValue(defaultTimeCount);
					jProgressBarTimer.setString(String.valueOf(defaultTimeCount));
				}
				{
					jButtonHelp = new JButton();
					MessagePanel.add(jButtonHelp);
					jButtonHelp.setText("\u5e2e\u52a9");
					jButtonHelp.setBounds(7, 12, 86, 22);
					jButtonHelp.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							jButtonHelpActionPerformed(evt);
						}
					});
				}
				{
					jButton2 = new JButton();
					MessagePanel.add(jButton2);
					jButton2.setText("\u8f6c\u6362");
					jButton2.setBounds(7, 413, 86, 22);
					jButton2.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							jButton2ActionPerformed(evt);
						}
					});
				}
			}
			{
				jScrollPane1 = new JScrollPane();
				getContentPane().add(jScrollPane1, BorderLayout.CENTER);
				jScrollPane1.setPreferredSize(new java.awt.Dimension(916, 687));
				jScrollPane1.setSize(910, 678);
				{
					mainPanel = new JPanel();
					jScrollPane1.setViewportView(mainPanel);
					mainPanel.setLayout(mainPanelCardLayout);
					mainPanel.setPreferredSize(new java.awt.Dimension(915, 660));
					mainPanel.setSize(910, 678);
					{
						hallPanel = new JPanel();
						hallPanel.setBackground(new Color(81, 113, 158));
						GridLayout hallPanelLayout = new GridLayout(3, 3);
						hallPanelLayout.setColumns(3);
						hallPanelLayout.setRows(3);
						mainPanel.add(hallPanel, "hallPanel");
						hallPanel.setLayout(hallPanelLayout);
						hallPanel.setPreferredSize(new java.awt.Dimension(917, 672));
						hallPanel.setSize(915, 661);
					}
				}
			}
			{
				statePanel = new JPanel();
				statePanel.setLayout(null);
				getContentPane().add(statePanel, BorderLayout.SOUTH);
				statePanel.setPreferredSize(new java.awt.Dimension(1016, 26));
				{
					jLabelPosMessage = new JLabel();
					statePanel.add(jLabelPosMessage);
					jLabelPosMessage.setText(" x=0 y=0");
					jLabelPosMessage.setBounds(0, 0, 228, 26);
				}
				{
					jLabelSysMsg = new JLabel();
					statePanel.add(jLabelSysMsg);
					jLabelSysMsg.setBounds(234, 0, 209, 26);
					jLabelSysMsg.setText("msg");
				}
				{
					jLabelCurrentPlayer = new JLabel();
					statePanel.add(jLabelCurrentPlayer);
					jLabelCurrentPlayer.setText("当前走棋");
					jLabelCurrentPlayer.setBounds(461, 0, 87, 26);
				}
			}
			{
				otherPanel = new JPanel();
				getContentPane().add(otherPanel, BorderLayout.WEST);
				otherPanel.setPreferredSize(new java.awt.Dimension(0, 636));
			}
			pack();
			this.setSize(1024, 735);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initHallPanel() {
		Hashtable<Integer, ChessDesk> desks = dataService.getDesks();
		dp = new HallDeskPanel[CONSTS.defaultDeskNum];
		for (int i = 0; i < CONSTS.defaultDeskNum; i++) {
			ChessDesk dsk = desks.get(i);
			if (dsk == null) {
				logger.error("客户端错误， dsk为null，可能没有登录！");
				break;
			}
			dp[i] = new HallDeskPanel(this, dsk);
			hallPanel.add(dp[i]);
		}
	}

	public void refreshHallPanel() {
		Hashtable<Integer, ChessDesk> desks = dataService.getDesks();
		for (int i = 0; i < CONSTS.defaultDeskNum; i++) {
			dp[i].refresh(desks.get(i));
		}
	}

	/**
	 * 更新某一桌的布局
	 */
	public void updateHallPanelDesk(ChessDesk desk) {
		dp[desk.getDeskNum()].refresh(desk);
	}

	public void onSeat(Response response) {
		if (CONSTS.RESPONSE_OK == response.getRes()) {
			// ClientModel.setDesks(response.getDesks());
			changeLayout(response.getLayout());// 修改视角
			dataService.setLayout(response.getLayout());
			dataService.getPlayer().setStates(CONSTS.PLAYER_STATS_ONSEAT);
			dataService.setChessDesk(response.getChessDesk());
			// 初始化
			deskLayoutJPanel = new DeskLayoutJPanel(this);
			mainPanel.add(deskLayoutJPanel, "deskLayoutJPanel");
			deskLayoutJPanel.setPreferredSize(new java.awt.Dimension(915, 681));
			deskLayoutJPanel.setSize(910, 678);
			mainPanelCardLayout.show(mainPanel, "deskLayoutJPanel");// 转到 棋盘画面
			// 播放声音
			AudioPlayer.player.start(ringwav); // 播放
			// AudioPlayer.player.stop(music); // 停止
			logger.trace("client before CMD_SEC-->CMD_SEC_ONSEAT OK!");
		} else {
			dataService.getPlayer().setDeskNum(0);
			dataService.getPlayer().setSeatName(null);
			JOptionPane.showMessageDialog(this, "链接错误", "错误提示", JOptionPane.INFORMATION_MESSAGE, null);
			logger.trace("client before CMD_SEC-->CMD_SEC_ONSEAT error! message=" + response.getMessage());
		}
	}

	/**
	 * 处理返回移动结果
	 * 
	 * @param response
	 */
	public void onEatChess(Response response) {
		// 删除或移动位置
		if (response.getRes() == CONSTS.RESPONSE_OK) {
			deskLayoutJPanel.selectedChessManPanel = null;// 第一次点击选中的棋子
			deskLayoutJPanel.toChessManPanel = null;// 第二次点击选中的棋子
			dataService.setChessDesk(response.getChessDesk());
			changeLayout(response.getLayout());// 修改视角
			dataService.setLayout(response.getLayout());// 本地修改布局
			// TODO 根据结果 播放声音
			AudioPlayer.player.start(movewav);
			// 更新颜色 开始计时
			updateSysMessage("完成吃旗，等待走棋。");
			updateCurrentPlayer(dataService.getOnTurn().name());
			deskLayoutJPanel.reDrawLayout();

			if (response.getSeatStates() == CONSTS.RESPONSE_EAT_WIN) {
				JOptionPane.showMessageDialog(this, "干掉一家，恭喜你！");
			} else if (response.getSeatStates() == CONSTS.RESPONSE_EAT_FAIL) {
				JOptionPane.showMessageDialog(this, "你输了！衰。。。");
			}

			showResState(response.getTeamStates());
		} else {
			// alert error
		}
	}

	public void resOnBoardEat(BoardBean bb) {
		dataService.setChessDesk(bb.getChessDesk());
		changeLayout(bb.getLayout());// 修改视角
		dataService.setLayout(bb.getLayout());// 本地修改布局

		// TODO 根据结果 播放声音
		AudioPlayer.player.start(movewav);
		updateSysMessage("完成吃旗。");
		updateCurrentPlayer(dataService.getOnTurn().name());
		deskLayoutJPanel.reDrawLayout();

		showResState(bb.getTeamStates());
	}

	public void onMoveChess(Response response) {
		logger.trace("client on eat res manstates=" + response.getChessManStates());
		// 删除或移动位置
		if (response.getRes() == CONSTS.RESPONSE_OK) {
			deskLayoutJPanel.selectedChessManPanel = null;// 第一次点击选中的棋子
			dataService.setChessDesk(response.getChessDesk());
			changeLayout(response.getLayout());// 修改视角
			dataService.setLayout(response.getLayout());// 本地修改布局
			// TODO 根据结果 播放声音
			AudioPlayer.player.start(movewav);
			updateSysMessage("完成走旗，等待走棋。");
			updateCurrentPlayer(dataService.getOnTurn().name());
			deskLayoutJPanel.reDrawLayout();
			beginTimeCount(dataService.getOnTurn());// 开始倒计时
		} else {
			// alert error
			System.out.println("response state error");
		}
	}

	public void resOnBoardMove(BoardBean bb) {
		dataService.setChessDesk(bb.getChessDesk());
		changeLayout(bb.getLayout());// 修改视角
		dataService.setLayout(bb.getLayout());// 本地修改布局

		// TODO 根据结果 播放声音
		AudioPlayer.player.start(movewav);
		updateSysMessage("完成走棋。");
		updateCurrentPlayer(dataService.getOnTurn().name());
		deskLayoutJPanel.reDrawLayout();
		beginTimeCount(dataService.getOnTurn());// 开始倒计时
	}

	/**
	 * 返回完成调度结果
	 * 
	 * @param evt
	 */
	public void onReady(Response response) {
		if (CONSTS.RESPONSE_OK == response.getRes()) {
			jButtonReady.setEnabled(false);
			dataService.setChessDesk(response.getChessDesk());
			changeLayout(response.getLayout());// 修改视角
			dataService.setLayout(response.getLayout());
			if (DESK_STATE.PLAYING == response.getChessDesk().getDeskStates()) {
				dataService.getPlayer().setStates(CONSTS.PLAYER_STATS_PLAYING);
				updateSysMessage("完成调度，等待走棋。");
				updateCurrentPlayer(dataService.getOnTurn().name());
				AudioPlayer.player.start(beginwav); // 播放
				beginTimeCount(dataService.getOnTurn());// 开始倒计时
				System.out.println("begin playing on board!");
			} else {
				dataService.getPlayer().setStates(CONSTS.PLAYER_STATS_READY);
				AudioPlayer.player.start(startwav); // 播放
				updateSysMessage("完成调度，等待所有人完成调度。");
			}
			jButtonSurrender.setEnabled(true);
			deskLayoutJPanel.reDrawLayout();
		} else {
			System.out.println("client begin error " + response.getMessage());
			return;
		}
		// 开始倒计时
	}

	/**
	 * 返回完成调度结果
	 * 
	 * @param evt
	 */
	public void onBoardReady(BoardBean bb) {
		dataService.setChessDesk(bb.getChessDesk());
		changeLayout(bb.getLayout());// 修改视角
		if (CONSTS.PLAYER_STATS_ONSEAT == dataService.getPlayer().getStates()) {
			commonLayoutService.copyLayout(dataService.getLayout(), bb.getLayout(), dataService.getPlayer().getSeatName());
		}
		dataService.setLayout(bb.getLayout());// 合并之后再复制回来
		if (dataService.getChessDesk().getDeskStates().equals(DESK_STATE.PLAYING)) {
			dataService.getPlayer().setStates(CONSTS.PLAYER_STATS_PLAYING);
			AudioPlayer.player.start(beginwav); // 播放
			beginTimeCount(dataService.getOnTurn());// 开始倒计时
			System.out.println("begin playing on board!");
		} else {
			AudioPlayer.player.start(startwav);
		}
		jButtonSurrender.setEnabled(true);
		updateSysMessage("完成调度，等待走棋。");
		updateCurrentPlayer(dataService.getOnTurn().name());
		//
		deskLayoutJPanel.reDrawLayout();

		// 开始倒计时
	}

	/**
	 * 点击完成调度按钮
	 * 
	 * @param evt
	 */
	private void jButtonReadyActionPerformed(ActionEvent evt) {
		// 发送布局
		// CommonLayoutService ls = new CommonLayoutService();
		ChessMan[][] layout = new ChessMan[13][20];// 只发送自己的布局13×20
		commonLayoutService.copyLayout(dataService.getLayout(), layout, dataService.getPlayer().getSeatName());

		ChessPackage cp = new ChessPackage(CONSTS.CMD_SEC, dataService.getPlayer().getId());
		Request request = new Request();
		request.setCommand(CONSTS.CMD_SEC_READY);
		request.setDeskNum(dataService.getPlayer().getDeskNum());
		request.setSeatName(dataService.getPlayer().getSeatName());
		changeLayout(layout);// 修改视角
		request.setLayout(layout);

		byte[] serRequest = null;
		try {
			serRequest = SerialUtil.enSerial(request);
		} catch (IOException e1) {
			e1.printStackTrace();
			return;
		}
		serRequest = Secret.encryptMsg(serRequest, dataService.getPlayer().getDesKey());
		cp.setContent(serRequest);

		// 发送请求
		control.sendRequest(cp);
	}

	public void onBoardLogout(BoardBean bb) {
		dataService.setChessDesk(bb.getChessDesk());
		// 如果在下棋状态就不更新
		if (CONSTS.PLAYER_STATS_LOGIN == dataService.getPlayer().getStates()) {
			dp[bb.getChessDesk().getDeskNum()].refresh(bb.getChessDesk());
		}
		changeLayout(bb.getLayout());// 修改视角
		if (CONSTS.PLAYER_STATS_ONSEAT == dataService.getPlayer().getStates()) {
			commonLayoutService.copyLayout(dataService.getLayout(), bb.getLayout(), dataService.getPlayer().getSeatName());
		}
		dataService.setLayout(bb.getLayout());// 合并之后再复制回来
		if (dataService.getChessDesk().getDeskStates().equals(DESK_STATE.PLAYING)) {
			dataService.getPlayer().setStates(CONSTS.PLAYER_STATS_PLAYING);
			AudioPlayer.player.start(beginwav); // 播放
			beginTimeCount(dataService.getOnTurn());// 开始倒计时
			System.out.println("begin playing on board!");
		} else {
			AudioPlayer.player.start(startwav);
		}
		jButtonSurrender.setEnabled(true);
		updateSysMessage("完成调度，等待走棋。");
		updateCurrentPlayer(dataService.getOnTurn().name());
		deskLayoutJPanel.reDrawLayout();
	}

	/**
	 * 返回完成调度结果
	 * 
	 * @param evt
	 */
	public void onExit(Response response) {
		if (CONSTS.RESPONSE_OK == response.getRes()) {
			// mainPanelCardLayout.show(mainPanel, "hallPanel");

			// 关闭端口
			// control.getMinaClient().close();
			this.dispose();
			// 退出本局比赛
			// 是否已开始
			// 显示大厅
			System.exit(0);
		} else {
			System.out.println("client begin error " + response.getMessage());
			return;
		}
	}

	private void jButtonExitActionPerformed(ActionEvent evt) {
		String msg = "";
		if (dataService.getPlayer().getStates() == CONSTS.PLAYER_STATS_PLAYING) {
			msg = "游戏进行中，确定要退出？";
		} else {
			msg = "确定要退出？";
		}
		int n = JOptionPane.showConfirmDialog(this, msg, "警告", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
		if (JOptionPane.YES_OPTION != n) {
			return;
		}

		//
		ChessPackage cp = new ChessPackage(CONSTS.CMD_SEC, dataService.getPlayerID());
		Request request = new Request();
		request.setCommand(CONSTS.CMD_SEC_LOGOUT);

		byte[] serRequest = null;
		try {
			serRequest = SerialUtil.enSerial(request);
		} catch (IOException e1) {
			e1.printStackTrace();
			return;
		}
		serRequest = Secret.encryptMsg(serRequest, dataService.getPlayer().getDesKey());
		cp.setContent(serRequest);

		// 发送请求
		control.sendRequest(cp);
	}

	private void jButton1ActionPerformed(ActionEvent evt) {
		//
		ChessPackage cp = new ChessPackage(CONSTS.CMD_SEC, dataService.getPlayerID());
		Request request = new Request();
		request.setCommand(CONSTS.CMD_SEC_MESSAGE);
		request.setMessage("这是一个测试test！");
		byte[] serRequest = null;
		try {
			serRequest = SerialUtil.enSerial(request);
		} catch (IOException e1) {
			e1.printStackTrace();
			return;
		}
		serRequest = Secret.encryptMsg(serRequest, dataService.getPlayer().getDesKey());
		cp.setContent(serRequest);

		// 发送请求
		control.sendRequest(cp);
	}

	/**
	 * 显示广播信息 测试
	 * 
	 * @param message
	 */
	public void showMsg(String message) {
		JOptionPane.showMessageDialog(this, message);
	}

	private void jButtonSurrenderActionPerformed(ActionEvent evt) {
		if (dataService.getPlayer().getStates() != CONSTS.PLAYER_STATS_PLAYING) {
			JOptionPane.showMessageDialog(this, "你的状态错误！");
			return;
		}

		if (JOptionPane.YES_OPTION != JOptionPane.showConfirmDialog(this, "确定要投降？", "提示信息", JOptionPane.YES_NO_OPTION)) {
			return;
		}
		//
		ChessPackage cp = new ChessPackage(CONSTS.CMD_SEC, dataService.getPlayerID());
		Request request = new Request();
		request.setCommand(CONSTS.CMD_SEC_SURRENDER);

		byte[] serRequest = null;
		try {
			serRequest = SerialUtil.enSerial(request);
		} catch (IOException e1) {
			e1.printStackTrace();
			return;
		}
		serRequest = Secret.encryptMsg(serRequest, dataService.getPlayer().getDesKey());
		cp.setContent(serRequest);

		// 发送请求
		control.sendRequest(cp);
	}

	public void resOnSurrender(Response response) {
		logger.trace("client on surrender res getTeamStates=" + response.getTeamStates());
		// 删除或移动位置
		if (response.getRes() == CONSTS.RESPONSE_OK) {
			deskLayoutJPanel.selectedChessManPanel = null;// 第一次点击选中的棋子
			dataService.setChessDesk(response.getChessDesk());
			changeLayout(response.getLayout());// 修改视角
			dataService.setLayout(response.getLayout());// 本地修改布局
			updateSysMessage("已投降。");
			updateCurrentPlayer(dataService.getOnTurn().name());
			deskLayoutJPanel.reDrawLayout();

			showResState(response.getTeamStates());
		} else {
			// alert error
		}
	}

	public void resOnBoardSurrender(BoardBean bb) {
		logger.trace("client on board surrender chessmanstate=" + bb.getChessManStates());

		dataService.setChessDesk(bb.getChessDesk());
		changeLayout(bb.getLayout());// 修改视角
		dataService.setLayout(bb.getLayout());// 本地修改布局
		updateSysMessage("投降。");
		updateCurrentPlayer(dataService.getOnTurn().name());
		deskLayoutJPanel.reDrawLayout();

		showResState(bb.getTeamStates());
	}

	/**
	 * 更新坐标信息
	 * 
	 * @param msg
	 */
	public void updatePosMessage(String msg) {
		jLabelPosMessage.setText(msg);
	}

	/**
	 * 更新系统信息
	 * 
	 * @param msg
	 */
	public void updateSysMessage(String msg) {
		jLabelSysMsg.setText(msg);
	}

	/**
	 * 更新系统信息
	 * 
	 * @param msg
	 */
	public void updateCurrentPlayer(String msg) {
		jLabelCurrentPlayer.setText(msg);
	}

	public JButton getJButtonReady() {
		return jButtonReady;
	}

	public DeskLayoutJPanel getDeskLayoutJPanel() {
		return deskLayoutJPanel;
	}

	public void setDeskLayoutJPanel(DeskLayoutJPanel deskLayoutJPanel) {
		this.deskLayoutJPanel = deskLayoutJPanel;
	}

	private void beginTimeCount(final SEAT_NAME onturn) {
		if (countTimer != null) {
			countTimer.stop();
		}
		System.out.println(onturn.name() + " " + dataService.getSeatColor(onturn));
		jProgressBarTimer.setForeground(dataService.getSeatColor(onturn));
		jProgressBarTimer.setValue(defaultTimeCount);
		jProgressBarTimer.setString(String.valueOf(defaultTimeCount));
		jProgressBarTimer.repaint();
		currentTimeCount = defaultTimeCount;
		ActionListener listener = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (currentTimeCount-- <= 0) {
					countTimer.stop();
					if (dataService.getOnTurn().equals(dataService.getPlayer().getSeatName())) {
						timeCountOver();
					}
				} else {
					jProgressBarTimer.setValue(currentTimeCount);
					jProgressBarTimer.setString(onturn.name() + " " + String.valueOf(currentTimeCount));
				}
			}
		};
		countTimer = new Timer(1000, listener);
		countTimer.start();
	}

	public void endTimeCount() {
		countTimer.stop();
	}

	private void timeCountOver() {
		ChessPackage cp = new ChessPackage(CONSTS.CMD_SEC, dataService.getPlayerID());
		Request request = new Request();
		request.setCommand(CONSTS.CMD_SEC_OVERTIME);
		byte[] serRequest = null;
		try {
			serRequest = SerialUtil.enSerial(request);
		} catch (IOException e1) {
			e1.printStackTrace();
			return;
		}
		serRequest = Secret.encryptMsg(serRequest, dataService.getPlayer().getDesKey());
		cp.setContent(serRequest);

		// 发送请求
		control.sendRequest(cp);
	}

	/**
	 * 超时三次算输
	 * 
	 * @param response
	 */
	public void resOverTime(Response response) {
		// 删除或移动位置
		if (response.getRes() == CONSTS.RESPONSE_OK) {
			deskLayoutJPanel.selectedChessManPanel = null;// 第一次点击选中的棋子
			dataService.setChessDesk(response.getChessDesk());
			changeLayout(response.getLayout());// 修改视角
			dataService.setLayout(response.getLayout());// 本地修改布局
			updateSysMessage("已超时。");
			updateCurrentPlayer(dataService.getOnTurn().name());
			deskLayoutJPanel.reDrawLayout();

			showResState(response.getTeamStates());
		} else {
			updateSysMessage("已超时 返回值错误。");
		}
	}

	public void resOnBoardOverTime(BoardBean bb) {
		dataService.setChessDesk(bb.getChessDesk());
		changeLayout(bb.getLayout());// 修改视角
		dataService.setLayout(bb.getLayout());// 本地修改布局
		updateSysMessage("超时。");
		updateCurrentPlayer(dataService.getOnTurn().name());
		deskLayoutJPanel.reDrawLayout();

		showResState(bb.getTeamStates());
	}

	private void showResState(int teamStates) {
		if (teamStates == CONSTS.RESPONSE_EAT_WIN) {
			JOptionPane.showMessageDialog(this, "本局赢，比赛结束");
			mainPanelCardLayout.show(mainPanel, "hallPanel");// 转到 大厅画面
		} else if (teamStates == CONSTS.RESPONSE_EAT_FAIL) {
			JOptionPane.showMessageDialog(this, "本局失败，比赛结束");
			mainPanelCardLayout.show(mainPanel, "hallPanel");// 转到 大厅画面
		} else {
			beginTimeCount(dataService.getOnTurn());// 开始倒计时
		}
	}

	private void jButtonHelpActionPerformed(ActionEvent evt) {
		HelpJDialog inst = new HelpJDialog(this);
		inst.setLocationRelativeTo(null);
		inst.setVisible(true);
	}

	private void changeLayout(ChessMan[][] layout) {
		if (CONSTS.SYS_CFG_CHESS_CONVERT) {
			SEAT_NAME sn = dataService.getPlayer().getSeatName();
			if (sn.equals(SEAT_NAME.S1) || sn.equals(SEAT_NAME.S2) || sn.equals(SEAT_NAME.S3) || sn.equals(SEAT_NAME.S4)) {
				commonLayoutService.changeVisualAngle(layout);
			}
		}
	}
	
	private void jButton2ActionPerformed(ActionEvent evt) {
		mainPanelCardLayout.show(mainPanel, "hallPanel");// 转到 大厅画面
	}
	// public void windowActivated(WindowEvent e) {
	//		
	// }
	//
	// public void windowClosed(WindowEvent e) {
	//		
	// }
	//
	// public void windowDeactivated(WindowEvent e) {
	//		
	// }
	//
	// public void windowDeiconified(WindowEvent e) {
	//		
	// }
	//
	// public void windowIconified(WindowEvent e) {
	//		
	// }
	//
	// public void windowOpened(WindowEvent e) {
	//		
	// }
	//
	// public void windowClosing(WindowEvent e) {
	// int option = JOptionPane.showConfirmDialog(this, "确定退出系统?", "提示",
	// JOptionPane.YES_NO_CANCEL_OPTION);
	// if (option == JOptionPane.YES_OPTION)
	// if (e.getWindow() == this) {
	// System.exit(0);
	// } else {
	// return;
	//
	// }
	// }

}
